<?php

namespace app\admin\controller;

use app\admin\validate\SysConfig as SysConfigValidate;
use app\common\business\SysConfig as SysConfigBus;
use app\common\lib\toCamelCase;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysConfig extends AuthBase
{
    //根据参数键名查询参数数据信息
    public function getConfigKey(){
        try {
            $configKey = $this->request->param("configKey","","trim");
            if(empty($configKey)){
                $configData = [];
            }else{
                $configData = (new SysConfigBus())->getConfigData($configKey);
            }
        }catch (\Exception $e){
            $configData = [];
        }
        return show(config("status.success"),$configData['config_value']);
    }

    //获取参数数据列表查询条件
    public function configListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $configName = $this->request->param('configName',"");
        $configKey = $this->request->param('configKey',"");
        $configType = $this->request->param("configType","");
        $params = $this->request->get('params',"");
        if($configName){
            $where[] = ['config_name', 'like', '%'.$configName.'%'];
        }
        if($configKey){
            $where[] = ['config_key', 'like', '%'.$configKey.'%'];
        }
        if($configType){
            $where[] = ['config_type', '=', $configType];
        }
        if($params){
            $where[] = ['create_time',">=",$params['beginTime']." 00:00:00"];
            $where[] = ['create_time',"<=",$params['endTime']." 23:59:59"];
        }
        $data = [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
        ];
        return $data;
    }

    //参数数据列表
    public function configList(){
        $searchData = $this->configListSearch();
        try {
            $configData = (new SysConfigBus())->getNormalConfigData($searchData['where'],'*',$searchData['limit'],$searchData['page']);
            $configData = (new toCamelCase())->toCamelCaseArray($configData);
        }catch (\Exception $e){
            $configData = [];
        }
        return show(config("status.success"),"参数数据列表",$configData);
    }

    //参数数据添加
    public function configAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $validate = new SysConfigValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            $result = (new SysConfigBus())->addConfig($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"新增成功",$result);
    }

    //参数数据修改
    public function configEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        try {
            $result = (new SysConfigBus())->updateById($data['config_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改成功",$result);
    }

    //删除参数数据
    public function configDel(){
        $config = $this->request->param("config","","trim");
        if(empty($config)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SysConfigBus())->DelConfigIds($config);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //参数数据详情
    public function configDetails(){
        $config = $this->request->param("config","","trim");
        if(empty($config)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $configData = (new SysConfigBus())->getConfigById($config);
            $configData = (new toCamelCase())->toCamelCaseArray($configData);
        }catch (\Exception $e){
            $configData = [];
        }
        return show(config("status.success"),"参数数据详情",$configData);
    }

    //导出参数数据信息
    public function exportConfig(){
        $searchData = $this->configListSearch();
        $configData = (new SysConfigBus())->getNormalConfigData($searchData['where'],'*',$searchData['limit'],$searchData['page']);

        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:H1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '字典类型数据信息');
        // 设置表头
        $header = ['参数主键', '参数名称', '参数键名', '参数键值', '系统内置','备注','创建时间'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F','G']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(21);
        }
        // 填充数据
        $row = 3;
        foreach ($configData['data'] as $post) {
            $post['config_type'] = $post['config_type'] === 'N' ? "否" : "是";
            $sheet->setCellValue('A' . $row, $post['config_id']);
            $sheet->setCellValue('B' . $row, $post['config_name']);
            $sheet->setCellValue('C' . $row, $post['config_key']);
            $sheet->setCellValue('D' . $row, $post['config_value']);
            $sheet->setCellValue('E' . $row, $post['config_type']);
            $sheet->setCellValue('F' . $row, $post['remark']);
            $sheet->setCellValue('G' . $row, $post['create_time']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:G2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:G2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':G' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':G' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="post.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }

    //刷新缓存
    public function clearCache($prefix = ''){
        return show(config("status.success"),"缓存刷新成功");
    }
}
